/*
 * LeveyTabBarController
 * @description 本文件提供本app使用的定制的TabBarController文件
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供本app使用的定制的TabBarController文件
 */

#import "LeveyTabBarController.h"
#import "LeveyTabBar.h"
#import "BanBu_ThemeManager.h"
#import "BanBu_NavigationController.h"
#import "BanBu_ListViewController.h"
#import "BanBu_BroadcastTVC.h"
#import "BanBu_DialogueController.h"
#import "BanBu_MyFriendViewController.h"
#import "BanBu_MySpaceViewController.h"
#import "BanBu_RefreshTime.h"
#import "BanBu_AppDelegate.h"
#import "CustomStatueBar.h"
#import "BanBu_FunctionGuide.h"

float kTabBarHeight = 64.0f;

static LeveyTabBarController *leveyTabBarController;

@implementation UIViewController (LeveyTabBarControllerSupport)

- (LeveyTabBarController *)leveyTabBarController
{
	return leveyTabBarController;

}
@end

@interface LeveyTabBarController (private)
- (void)displayViewAtIndex:(NSUInteger)index;
@end

@implementation LeveyTabBarController
@synthesize delegate = _delegate;
@synthesize selectedViewController = _selectedViewController;
@synthesize viewControllers = _viewControllers;
@synthesize selectedIndex = _selectedIndex;
@synthesize tabBarHidden = _tabBarHidden;

#pragma mark -
#pragma mark lifecycle
- (id)initWithViewControllers:(NSArray *)vcs imageArray:(NSArray *)arr;
{
	self = [super init];
	if (self != nil)
	{
        NSLog(@"123456765");
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeTheme) name:kThemeDidChangeNotification object:nil];
		_viewControllers = [[NSMutableArray arrayWithArray:vcs] retain];
		_containerView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
        
        _transitionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320.0f, _containerView.frame.size.height - kTabBarHeight)];
        _tabBar = [[LeveyTabBar alloc] initWithFrame:CGRectMake(0, _containerView.frame.size.height - kTabBarHeight, 320.0f, kTabBarHeight)];
        
		_transitionView.backgroundColor =  [UIColor groupTableViewBackgroundColor];
        [self changeTheme];
		_tabBar.delegate = self;
        leveyTabBarController = self;
	}
	return self;
}


- (void)loadView
{
	[super loadView];
	
	[_containerView addSubview:_transitionView];
	[_containerView addSubview:_tabBar];
	self.view = _containerView;
}
-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

-(BOOL)prefersStatusBarHidden
{
    return NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.selectedIndex = 0;

    if([[[UIDevice currentDevice] systemVersion] floatValue]>=7.0)
    {
        [self setNeedsStatusBarAppearanceUpdate];
    }
    self.statueBar= [[[CustomStatueBar alloc]initWithFrame:CGRectMake(220, 0, 100, 20)] autorelease];
}

-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
    if(_tabBar.frame.origin.y!=_containerView.frame.size.height)
    {
        _tabBar.frame = CGRectMake(0, _containerView.frame.size.height - kTabBarHeight, 320.0f, kTabBarHeight);
    }
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if(IS_IOS_7)
    {
        _transitionView.frame = CGRectMake(0, 0, 320.0f, _containerView.frame.size.height);
    }
    UINavigationController *nav = [self.viewControllers objectAtIndex:self.selectedIndex];
    if([nav isMemberOfClass:[BanBu_NavigationController class]])
    {
        if(self.selectedIndex == 0)
        {
            //判断是否要刷新页面
            NSString *timeNowString = [BanBu_RefreshTime getCurrentTime:nil];
            BOOL isReload = [BanBu_RefreshTime now:timeNowString isLaterBefore:[UserDefaults valueForKey:@"nearby_updateTime"]];
            if(isReload&&[(BanBu_ListViewController*)[nav.viewControllers objectAtIndex:0] isViewLoaded])
            {
                [(BanBu_ListViewController*)[nav.viewControllers objectAtIndex:0] setRefreshing];
            }
        }
        else if(self.selectedIndex == 1)
        {
            NSString *timeNowString = [BanBu_RefreshTime getCurrentTime:nil];
            BOOL isReload = [BanBu_RefreshTime now:timeNowString isLaterBefore:[UserDefaults valueForKey:@"squares_updateTime"]];
            
            BanBu_AppDelegate *delegate = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
            
            if(isReload&&[(BanBu_BroadcastTVC*)[nav.viewControllers objectAtIndex:0] isViewLoaded] && delegate.logined)
            {
                [(BanBu_BroadcastTVC *)[nav.viewControllers objectAtIndex:0] setRefreshing];
                
            }
        }
    }
}
- (void)viewDidUnload
{
	[super viewDidUnload];
	_tabBar = nil;
	_viewControllers = nil;
    _isFirstIn = YES;
}


- (void)dealloc
{
    [_statueBar release],_statueBar = nil;
    _tabBar.delegate = nil;
	[_tabBar release],_tabBar = nil;
    [_containerView release],_containerView = nil;
    [_transitionView release],_transitionView = nil;
	[_viewControllers release],_viewControllers = nil;
    [[NSNotificationCenter defaultCenter]removeObserver:self name:kThemeDidChangeNotification object:nil];
    [super dealloc];
}
-(void)changeTheme
{
    kTabBarHeight = ThemeManager.tabbarHeight;
    
    if(kTabBarHeight == 0)
    {
        kTabBarHeight  = 49;
    }
    self.tabBar.backgroundView.image = nil;
    
    [self.tabBar setBackgroundImage:[ThemeManager getThemeImage:@"tabbarImage.png"]];
    NSMutableDictionary *imgDic = [NSMutableDictionary dictionaryWithCapacity:3];
	[imgDic setObject:[ThemeManager getThemeImage:@"nearby.png"] forKey:@"Default"];
	[imgDic setObject:[ThemeManager getThemeImage:@"nearby_selected.png"] forKey:@"Highlighted"];
	[imgDic setObject:[ThemeManager getThemeImage:@"nearby_selected.png"] forKey:@"Seleted"];
	NSMutableDictionary *imgDic2 = [NSMutableDictionary dictionaryWithCapacity:3];
	[imgDic2 setObject:[ThemeManager getThemeImage:@"throwball.png"] forKey:@"Default"];
	[imgDic2 setObject:[ThemeManager getThemeImage:@"throwball_selected.png"] forKey:@"Highlighted"];
	[imgDic2 setObject:[ThemeManager getThemeImage:@"throwball_selected.png"] forKey:@"Seleted"];
	NSMutableDictionary *imgDic3 = [NSMutableDictionary dictionaryWithCapacity:3];
	[imgDic3 setObject:[ThemeManager getThemeImage:@"chat.png"] forKey:@"Default"];
	[imgDic3 setObject:[ThemeManager getThemeImage:@"chat_selected.png"] forKey:@"Highlighted"];
	[imgDic3 setObject:[ThemeManager getThemeImage:@"chat_selected.png"] forKey:@"Seleted"];
	NSMutableDictionary *imgDic4 = [NSMutableDictionary dictionaryWithCapacity:3];
	[imgDic4 setObject:[ThemeManager getThemeImage:@"myfriend.png"] forKey:@"Default"];
	[imgDic4 setObject:[ThemeManager getThemeImage:@"myfriend_selected.png"] forKey:@"Highlighted"];
	[imgDic4 setObject:[ThemeManager getThemeImage:@"myfriend_selected.png"] forKey:@"Seleted"];
	NSMutableDictionary *imgDic5 = [NSMutableDictionary dictionaryWithCapacity:3];
	[imgDic5 setObject:[ThemeManager getThemeImage:@"myapplication.png"] forKey:@"Default"];
	[imgDic5 setObject:[ThemeManager getThemeImage:@"myapplication_selected.png"] forKey:@"Highlighted"];
	[imgDic5 setObject:[ThemeManager getThemeImage:@"myapplication_selected.png"] forKey:@"Seleted"];
	NSArray *imgArr = [NSArray arrayWithObjects:imgDic,imgDic2,imgDic3,imgDic4,imgDic5,nil];
    
    NSArray *array = [NSArray   arrayWithObjects:NSLocalizedString(@"luckPeopleTitle", nil),
                      NSLocalizedString(@"broadcastTitle", nil),
                      NSLocalizedString(@"dialogueTitle", nil),
                      NSLocalizedString(@"myFriendTitle", nil),
                      NSLocalizedString(@"mySpaceTitle", nil),nil];
    int i = 0;
    if(self.tabBar.frame.origin.y == self.view.frame.size.height)
    {
        [_tabBar setThemeFrame:CGRectMake(0, self.view.frame.size.height, 320.0f, kTabBarHeight)];
    }
    else
        [_tabBar setThemeFrame:CGRectMake(0, _containerView.frame.size.height - kTabBarHeight, 320.0f, kTabBarHeight)];
    for(UIButton *button in self.tabBar.buttons)
    {
        [button setTitle:[array objectAtIndex:i] forState:UIControlStateNormal] ;
        [button setTitleEdgeInsets:UIEdgeInsetsMake(ThemeManager.tabbarHeight/2+10, 0, 0, 0)];
        button.titleLabel.textAlignment = kTextAlignmentCenter;
        button.titleLabel.font = [UIFont systemFontOfSize:10];
        i++;
    }
    [_tabBar reSetButtonImageArray:imgArr];
}
#pragma mark - instant methods

- (LeveyTabBar *)tabBar
{
	return _tabBar;
}
- (BOOL)tabBarTransparent
{
	return _tabBarTransparent;
}
- (void)setTabBarTransparent:(BOOL)yesOrNo
{
	if (yesOrNo == YES)
	{
		_transitionView.frame = _containerView.bounds;
	}
	else
	{
		_transitionView.frame = CGRectMake(0, 0, 320.0f, _containerView.frame.size.height - kTabBarHeight);
	}
}
- (void)hidesTabBar:(BOOL)yesOrNO animated:(BOOL)animated;
{
	if (yesOrNO == YES)
	{
		if (self.tabBar.frame.origin.y == self.view.frame.size.height)
		{
			return;
		}
	}
	else
	{
		if (self.tabBar.frame.origin.y == self.view.frame.size.height - kTabBarHeight)
		{
			return;
		}
	}
	
	if (animated == YES)
	{
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.3f];
		if (yesOrNO == YES)
		{
			self.tabBar.frame = CGRectMake(self.tabBar.frame.origin.x, self.tabBar.frame.origin.y + kTabBarHeight, self.tabBar.frame.size.width, self.tabBar.frame.size.height);
		}
		else
		{
			self.tabBar.frame = CGRectMake(self.tabBar.frame.origin.x, self.tabBar.frame.origin.y - kTabBarHeight, self.tabBar.frame.size.width, self.tabBar.frame.size.height);
		}
		[UIView commitAnimations];
	}
	else
	{
		if (yesOrNO == YES)
		{
			self.tabBar.frame = CGRectMake(self.tabBar.frame.origin.x, self.tabBar.frame.origin.y + kTabBarHeight, self.tabBar.frame.size.width, self.tabBar.frame.size.height);
		}
		else
		{
			self.tabBar.frame = CGRectMake(self.tabBar.frame.origin.x, self.tabBar.frame.origin.y - kTabBarHeight, self.tabBar.frame.size.width, self.tabBar.frame.size.height);
		}
	}
    
    
}

- (NSUInteger)selectedIndex
{
	return _selectedIndex;
}
- (UIViewController *)selectedViewController
{
    return [_viewControllers objectAtIndex:_selectedIndex];
}

-(void)setSelectedIndex:(NSUInteger)index
{
    [self displayViewAtIndex:index];
    [_tabBar selectTabAtIndex:index];
}

- (void)removeViewControllerAtIndex:(NSUInteger)index
{
    if (index >= [_viewControllers count])
    {
        return;
    }
    // Remove view from superview.
    [[(UIViewController *)[_viewControllers objectAtIndex:index] view] removeFromSuperview];
    // Remove viewcontroller in array.
    [_viewControllers removeObjectAtIndex:index];
    // Remove tab from tabbar.
    [_tabBar removeTabAtIndex:index];
}

- (void)insertViewController:(UIViewController *)vc withImageDic:(NSDictionary *)dict atIndex:(NSUInteger)index
{
    [_viewControllers insertObject:vc atIndex:index];
    [_tabBar insertTabWithImageDic:dict atIndex:index];
}


#pragma mark - Private methods
- (void)displayViewAtIndex:(NSUInteger)index
{
    // Before changing index, ask the delegate should change the index.
    if ([_delegate respondsToSelector:@selector(tabBarController:shouldSelectViewController:)])
    {
        if (![_delegate tabBarController:self shouldSelectViewController:[self.viewControllers objectAtIndex:index]])
        {
            return;
        }
    }
    
    UIViewController *targetViewController = [self.viewControllers objectAtIndex:index];
    
    // If target index is equal to current index.
    if (_selectedIndex == index && [[_transitionView subviews] count] != 0)
    {
        if ([targetViewController isKindOfClass:[UINavigationController class]]) {
            [(UINavigationController*)targetViewController popToRootViewControllerAnimated:YES];
        }
        return;
    }
    [[self.viewControllers objectAtIndex:_selectedIndex] viewWillDisappear:YES];
    _selectedIndex = index;
    
	[_transitionView.subviews makeObjectsPerformSelector:@selector(setHidden:) withObject:(id)YES];
    targetViewController.view.hidden = NO;
    [[self.viewControllers objectAtIndex:_selectedIndex] viewWillAppear:YES];
	targetViewController.view.frame = _transitionView.frame;
	if ([targetViewController.view isDescendantOfView:_transitionView])
	{
		[_transitionView bringSubviewToFront:targetViewController.view];
        [[self.viewControllers objectAtIndex:_selectedIndex] viewDidAppear:YES];
	}
	else
	{
		[_transitionView addSubview:targetViewController.view];
	}
    
    // Notify the delegate, the viewcontroller has been changed.
    if ([_delegate respondsToSelector:@selector(tabBarController:didSelectViewController:)])
    {
        [_delegate tabBarController:self didSelectViewController:targetViewController];
    }
}

#pragma mark -
#pragma mark tabBar delegates
- (void)tabBar:(LeveyTabBar *)tabBar didSelectIndex:(NSInteger)index
{
    NSLog(@"%@",NSStringFromCGRect(self.containerView.frame));
//    _containerView.frame = CGRectMake(0, 0, 320, 568);
    if(index == 0)
    {
        [[BanBu_FunctionGuide shareInstance] addFunctionGuideToPage:_containerView withKey:FunctionTargetNearby];
    }
    else if (index == 4)
    {
        [[BanBu_FunctionGuide shareInstance] addFunctionGuideToPage:_containerView withKey:FunctionTargetSpace];
    }

    if(index == self.selectedIndex)
    {

        UINavigationController *nav = [self.viewControllers objectAtIndex:index];
        if([nav isMemberOfClass:[BanBu_NavigationController class]])
        {
            if(self.selectedIndex == 0)
            {
                if([(BanBu_ListViewController*)[nav.viewControllers objectAtIndex:0] isViewLoaded])
                {
                    
                    [(BanBu_ListViewController*)[nav.viewControllers objectAtIndex:0] setRefreshing];
                }
            }
            else if(self.selectedIndex == 1)
            {
                if([(BanBu_BroadcastTVC*)[nav.viewControllers objectAtIndex:0] isViewLoaded])
                {
                    [(BanBu_BroadcastTVC *)[nav.viewControllers objectAtIndex:0] setRefreshing];
                }
            }
            else if(self.selectedIndex == 2)
            {
                if([(BanBu_DialogueController *)[nav.viewControllers objectAtIndex:0] isViewLoaded])
                {
                    if(MyAppDataManager.talkPeoples.count)
                    {
                        [[(BanBu_DialogueController *)[nav.viewControllers objectAtIndex:0] tableView] scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionNone animated:YES];
                    }
                }
            }
            else if(self.selectedIndex == 3)
            {
                if([(BanBu_MyFriendViewController*)[nav.viewControllers objectAtIndex:0] isViewLoaded])
                {
                    [(BanBu_MyFriendViewController*)[nav.viewControllers objectAtIndex:0] setRefreshing];
                }
            }
  
            [nav popToRootViewControllerAnimated:YES];
        }
    }
    _isFirstIn = NO;
	[self displayViewAtIndex:index];
}
@end
